package com.example.cursor_service.impl;

import com.example.cursor_service.PermissionService;
import com.example.cursor_orm.model.Permission;
import com.example.cursor_orm.dao.PermissionDAO;
import com.example.cursor_orm.dao.RolePermissionDAO;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.ArrayList;

@Service
public class PermissionServiceImpl implements PermissionService {
    private final PermissionDAO permissionDAO;
    private final RolePermissionDAO rolePermissionDAO;
    
    public PermissionServiceImpl(PermissionDAO permissionDAO, RolePermissionDAO rolePermissionDAO) {
        this.permissionDAO = permissionDAO;
        this.rolePermissionDAO = rolePermissionDAO;
    }
    
    @Override
    public Permission createPermission(Permission permission) {
        try {
            permissionDAO.insert(permission);
            return permission;
        } catch (Exception e) {
            return null;
        }
    }
    
    @Override
    public Permission getPermissionById(Integer id) {
        try {
            return permissionDAO.findById(id);
        } catch (Exception e) {
            return null;
        }
    }
    
    @Override
    public Permission updatePermission(Integer id, Permission permission) {
        try {
            permission.setId(id);
            permissionDAO.update(permission);
            return permissionDAO.findById(id);
        } catch (Exception e) {
            return null;
        }
    }
    
    @Override
    public boolean deletePermission(Integer id) {
        try {
            return permissionDAO.deleteById(id) > 0;
        } catch (Exception e) {
            return false;
        }
    }
    
    @Override
    public List<Permission> getPermissionList(int page, int size) {
        try {
            List<Permission> all = permissionDAO.findAll();
            int from = Math.max(0, (page - 1) * size);
            int to = Math.min(all.size(), from + size);
            return all.subList(from, to);
        } catch (Exception e) {
            return new ArrayList<>();
        }
    }
    
    @Override
    public List<Permission> getPermissionTree() {
        try {
            // 简单返回全部权限，实际可按父子结构组织
            return permissionDAO.findAll();
        } catch (Exception e) {
            return new ArrayList<>();
        }
    }
    
    @Override
    public boolean assignPermissionToRole(Integer permissionId, Integer roleId) {
        try {
            return rolePermissionDAO.assignPermissionToRole(roleId, permissionId) > 0;
        } catch (Exception e) {
            return false;
        }
    }
    
    @Override
    public boolean removePermissionFromRole(Integer permissionId, Integer roleId) {
        try {
            return rolePermissionDAO.removePermissionFromRole(roleId, permissionId) > 0;
        } catch (Exception e) {
            return false;
        }
    }
} 